package com.yc.study.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.study.entity.User;
import com.yc.study.service.IUserRoleService;
import com.yc.study.service.IUserService;
import com.yc.study.vo.ChangePasswordVo;
import com.yc.study.vo.RegisterVo;
import com.yc.study.vo.StudentCountVo;
import com.yc.study.vo.UserVo;
import lombok.AllArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.List;

/**
 * 前端控制器
 *
 * @author 王妍
 * @since 2022-02-20
 */
@RestController
@RequestMapping(value = "/study/user")
@AllArgsConstructor
public class UserController {
  private final IUserService userService;
  private final IUserRoleService userRoleService;

  @PostMapping("/registered")
  public void register(@RequestBody RegisterVo registerUser) {
    userService.register(registerUser);
  }

  @PutMapping("/password")
  public void changePassword(
      Principal principal, @RequestBody @Validated ChangePasswordVo changePasswordVo) {
    userService.changePassword(principal.getName(), changePasswordVo);
  }

  /**
   * 查询用户信息列表
   *
   * @param page 分页条件
   * @param userVo user info 参数
   * @return 用户分页信息
   */
  @GetMapping("page")
  public Page<UserVo> loadPageUser(Page<UserVo> page, UserVo userVo) {
    return userService.loadUserVoPage(page, userVo);
  }

  @GetMapping("student/page")
  public Page<UserVo> loadPageUser(Long taskId, Page<UserVo> page, UserVo userVo) {
    return userService.loadUserVoPage2(taskId,page, userVo);
  }

  @DeleteMapping("/{userId}")
  public void deleteById(@PathVariable("userId") Long userId) {
    userService.removeById(userId);
  }

  @DeleteMapping
  @Transactional(rollbackFor = Exception.class)
  public void deleteByUserIds(@RequestBody Long[] userIds) {
    userService.deleteAll(userIds);
  }

  @PutMapping
  public void update(@RequestBody UserVo userVo) {
    userService.saveInfo(userVo);
  }

  @GetMapping("teacher")
  public List<User> loadTeacherList() {
    return userService.loadTeacherList();
  }

  @GetMapping("checkIn/count")
  public StudentCountVo list(Long taskId){
    return  userService.list2(taskId);
  }
}
